import {addOperationApi, checkApi, checkPriceApi} from '@/api/operation'
import {resetForm} from "@/utils/common";
import SearchSelectAll from "@/views/components/EnabledSearchSelectAll";

export default {
  components: {SearchSelectAll},
  data() {
    return {
      state: null, // 0揽收 1发出 2到达 3待取件 4问题件 5签收
      isAutoSubmit: false,
      isAutoLoading: false,
      timer: null,
      hasSubmit: true, // 提交按钮
      errorList: [], // 无法操作的单号
      numberForm: {
        orders: ''
      },
      numberRules: {
        orders: {required: true, message: '请输入单号', trigger: 'blur'}
      },
      form: {
        numbers: '', // 单号
        state: null, // 状态
        notes: '', // 备注
        laosNotes: '',
        currentUserId: null, // 当前网点
        currentUserName: '',
        currentName: '',
        laosCurrentName: '',
        sendToUserId: null, // 发往网点
        sendToUserName: '',
        sendToName: '',
        laosSendToName: ''
      },
      rules: {
        sendToUserId: {required: true, message: '请选择发往网点', trigger: 'change'}
      }
    }
  },
  watch: {
    'numberForm.orders'(value) {
      if (value[value.length - 1] === '\n') {
        this.loadSound();
      }
    }
  },
  mounted() {
    this.init()
    // 持久化
    if (this.$storeGet.operation.includes(this.state)) {
      this.isAutoSubmit = true
      this.changeAuto(true)
    }
  },
  beforeDestroy() {
    this.resetAuto()
  },
  methods: {
    /**
     * @description 自动上传
     * */
    // 拼接错误单号
    joint(numbers) {
      if (!numbers) return
      if (typeof numbers === 'string') {
        numbers = numbers.split(',')
      }
      let length = this.numberForm.orders.length
      let last = this.numberForm.orders[length - 1]
      if (last === '\n' || last === undefined) {
        this.numberForm.orders += numbers.join('\n') + '\n'
      } else {
        this.numberForm.orders += '\n' + numbers.join('\n') + '\n'
      }
    },
    // 自动上传状态变化
    changeAuto(value) {
      if (value) {
        this.auto()
        this.$storeSet('addOperation', this.state)
      } else {
        this.resetAuto()
        this.$storeSet('delOperation', this.state)
      }
    },
    // 发生错误
    goWrong(text, list) {
      this.$errorNotify(text)
      this.resetAuto()
      this.joint(list)
      this.$storeSet('delOperation', this.state)
    },
    // 重置自动上传
    resetAuto() {
      this.isAutoSubmit = false
      this.isAutoLoading = false
      clearInterval(this.timer)
    },
    auto() {
      this.timer = setInterval(() => {
        if (!this.isAutoSubmit) return
        if (this.isAutoLoading) return
        if (!this.hasSubmit) {
          this.goWrong('余额低于警戒线，无法自动上传')
          return
        }
        if (this.state === 1 && !this.form.sendToUserId) {
          this.$errorMsg('未选择发往网点，无法自动上传')
          return
        }
        let value = this.numberForm.orders
        value = value.trim(); // 去空
        if (!value) return;
        this.numberForm.orders = ''
        let numbers = this.getString(value)
        let param = {
          state: this.state,
          numbers: numbers
        };
        let successList = []
        let errorList = []
        this.isAutoLoading = true
        // 检测单号
        checkApi(param).then(result => {
          if (result.status !== 200) {
            this.goWrong('检测单号期间发生错误，终止自动上传', numbers)
            return
          }
          successList = result.resultParam.successList
          let errorMap = result.resultParam.errorMap
          for (let key in errorMap) {
            if (Object.prototype.hasOwnProperty.call(errorMap, key) && errorMap[key].length !== 0) {
              errorList = [...errorList, ...errorMap[key]]
            }
          }

          if (successList.length > 0) { // 有成功单号，上传
            let data = {...this.form};
            data.numbers = successList.join(',')
            data.state = this.state;
            addOperationApi(data).then(result => {
              if (result.status !== 200) {
                this.goWrong('上传期间发生错误，终止自动上传', successList)
                return
              }
              this.isAutoLoading = false
            }).catch(() => {
              this.goWrong('上传期间发生错误，终止自动上传', successList)
            })
          } else {
            this.isAutoLoading = false
          }

          if (errorList.length > 0) { // 有失败单号,拼接
            this.joint(errorList)
          }
        }).catch(() => {
          this.goWrong('检测单号期间发生错误，终止自动上传', numbers)
        })
      }, 10000)
    },
    /**
     * */

    // 初始化
    init() {
      this.hasSubmit = true;
      this.form.currentUserId = this.$user.id;
      this.form.currentUserName = this.$user.username;
      this.form.currentName = this.$user.name;
      this.form.laosCurrentName = this.$user.laosName;
      checkPriceApi().then(result => {
        // 余额低于警戒线
        if (result.resultParam.isWarning) {
          this.hasSubmit = false;
          this.$warnMsg('余额低于警戒线，无法提交')
        }
      })
    },

    // 隐藏检测
    check() {
      let value = this.numberForm.orders.trim();
      if (!value) return
      checkApi({
        state: this.state,
        numbers: this.getString(value)
      })
    },

    // 手动提交
    submit: async function () {
      try {
        // 检测未填项
        this.$refs['Form'].validate(valid => {
          if (!valid) throw new Error();
        })

        // 检测单号
        let value = this.numberForm.orders.trim();
        if (!value) {
          this.$errorMsg('请输入单号')
          return
        }
        let param = {
          state: this.state,
          numbers: this.getString(value)
        };
        this.$refs.Card.start()
        await checkApi(param).then(result => {
          this.$refs.Card.stop();
          if (result.status !== 200) {
            this.form.numbers = ''
            return
          }
          this.form.numbers = result.resultParam.successList.join(',')
          this.sendErrorMsg(result.resultParam.errorMap)
        }).catch(() => {
          this.$refs.Card.stop();
          this.form.numbers = ''
        })

        // 上传单号
        if (!this.form.numbers) return
        let data = {...this.form};
        data.state = this.state;
        this.$startLoading();
        addOperationApi(data).then(result => {
          this.$stopLoading()
          if (result.status !== 200) return
          this.cancel();
        }).catch(() => {
          this.$stopLoading()
        })

        // eslint-disable-next-line no-empty
      } catch (e) {

      }
    },

    // 关闭
    cancel() {
      resetForm(this, 'numberForm', 'NumberForm')
        .then(() => {
          // 初始化
          this.init();
          // 单号
          this.form.numbers = ''
          // 错误单号
          if (this.errorList.length > 0) this.numberForm.orders = this.errorList.join('\n')
          // 清除验证
          this.$refs['Form'].clearValidate()
        })
    },

    // 发送错误信息
    sendErrorMsg(error) {
      this.errorList = [];
      const H = [];
      const h = this.$createElement;
      for (let key in error) {
        let keyName = '';
        if (key === 'numberNotArrive') keyName = '不能被到达：';
        if (key === 'numberNotSender') keyName = '不能被发出：';
        if (key === 'numberNotDelivery') keyName = '不能待取件：';
        if (key === 'numberNotSign') keyName = '不能被签收：';
        if (key === 'numberNotFoundList') keyName = '单号不存在：';
        if (key === 'numberNotUse') keyName = '单号未使用：';
        if (key === 'numberNotIssue') keyName = '单号不能被作为问题件：';
        if (key === 'stateReUseList') keyName = '单号已做过该操作：';
        // if (key === 'problemNotDeal') keyName = '问题件未处理：';
        if (key === 'problemNotDeal') continue;
        if (Object.prototype.hasOwnProperty.call(error, key) && error[key].length !== 0) {
          H.push(h('p', null, `${keyName}${error[key].join(' ')}`));
          this.errorList = [...this.errorList, ...error[key]]
        }
      }
      if (H.length === 0) return
      this.$errorMsg(h('p', {style: {color: '#F56C6C'}}, H));
    },

    // 获得单号字符串
    getString(value) {
      let list = [];
      value = value.split('\n');
      value.forEach(item => { // 去空格
        item = item.trim();
        if (item !== '') list.push(item)
      });
      for (let i = 0; i < list.length; i++) { // 去重
        for (let j = i + 1; j < list.length; j++) {
          if (list[i] === list[j]) {
            list.splice(j, 1);
            j--;
          }
        }
      }
      return list.join(',')
    },

    // 选择网点
    getSite(obj) {
      if (obj) {
        this.form.sendToUserId = obj.id;
        this.form.sendToUserName = obj.username;
        this.form.sendToName = obj.name;
        this.form.laosSendToName = obj.laosName;
      } else {
        this.form.sendToUserId = null;
        this.form.sendToUserName = '';
        this.form.sendToName = '';
        this.form.laosSendToName = '';
      }
    },

    // 回车提示音
    loadSound() {
      let con = new AudioContext();
      let req = new XMLHttpRequest();
      req.open('GET', '/assets/tips.mp3', true);
      req.responseType = 'arraybuffer';
      req.onload = function () {
        con.decodeAudioData(req.response, function (buffer) {
          let source = con.createBufferSource();
          source.buffer = buffer;
          source.connect(con.destination);
          source.start(0);
        }, function (e) {
          console.info(e);
        });
      };
      req.send();
    }
  }
}
